<script setup lang="ts">
  import { ref, reactive, onMounted, markRaw, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Warning } from '@element-plus/icons-vue'
  import type { FormInstance } from 'element-plus'
  import { getNetworkSet, saveNetworkSet } from '@/api/basic'
  import { empPageSelecct } from '@/api/organize'
  import InviteCodeSetForm from './components/InviteCodeSetForm.vue'
  import { useNetworkInviteCodeSetService } from './services/index'

  const loading = ref(false)

  // 使用服务
  const { saveNetworkInviteCodeFn, saveNetworkInviteCodeLoading } = useNetworkInviteCodeSetService

  // 邀请码表单实例
  const inviteCodeSetFormRef = ref<InstanceType<typeof InviteCodeSetForm> | null>(null)

  // 表单数据
  let form = reactive({
    autoCheckCancelOrder: false, // 取消工单策略
    autoCheckEndOrder: false, // 审核结单策略
    autoDispatchOrder: true, // 自动派单
    autoDispatchServiceStrategy: 2, // 分派客服
    empId: null, // 分配客服
    // enableChangeMaintenanceEmp: true,
    enableCreateOrder: true, // 新建工单
    enableScanReceive: true, // 扫码收款
    enableUpdateSparePrice: false, // 审核结单策略
    id: null,
    importReceiverVoucher: true, // 收款凭证
    sectorise: 1, // 区域限制
  })

  // 表单元素
  const formRef = ref<FormInstance>()

  // 获取服务商设置
  const getSet = async () => {
    loading.value = true
    const res = await getNetworkSet()
    if (res.data.success) {
      form.autoCheckCancelOrder = res.data.data.row.autoCheckCancelOrder
      form.autoCheckEndOrder = res.data.data.row.autoCheckEndOrder
      form.autoDispatchOrder = res.data.data.row.autoDispatchOrder
      form.autoDispatchServiceStrategy = res.data.data.row.autoDispatchServiceStrategy
      form.empId = res.data.data.row.empId
      // form.enableChangeMaintenanceEmp = res.data.data.row.enableChangeMaintenanceEmp
      form.enableCreateOrder = res.data.data.row.enableCreateOrder
      form.enableScanReceive = res.data.data.row.enableScanReceive
      form.enableUpdateSparePrice = res.data.data.row.enableUpdateSparePrice
      form.id = res.data.data.row.id
      form.importReceiverVoucher = res.data.data.row.importReceiverVoucher
      form.sectorise = res.data.data.row.sectorise
    } else {
      if (res.data.isError)
        ElMessage({
          message: res.data.message,
          type: 'error',
        })
    }
    loading.value = false
  }

  // 使用 ref 来缓存客服数据
  const customersData = ref([])

  // 获取客服
  const getworkTeamPageSelect = (val) => {
    if (customersData.value.length === 0) {
      // 仅当缓存中没有数据时才触发请求
      let data = {
        limit: 0,
        name: val,
        page: 0,
      }
      loading.value = true
      empPageSelecct(data).then((res) => {
        if (res.data.success) {
          customersData.value = res.data.data.rows
        }
        loading.value = false
      })
    }
  }
  const odlValue = ref()
  watch(
    () => form.sectorise,
    (n, o) => {
      odlValue.value = o
    },
  )
  // 保存服务商设置
  const saveSet = () => {
    ElMessageBox({
      type: 'warning',
      title: '提示',
      icon: markRaw(Warning),
      message: `确认保存修改的设置?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 10)
        } else {
          // setTimeout(() => {
          form.sectorise = odlValue.value
          done()
          // }, 0)
        }
      },
    })
      .then(async () => {
        await saveNetworkSet(form).then((res) => {
          if (res.data.success) {
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 2000,
            })
          } else {
            if (res.data.isError)
              ElMessage({
                message: res.data.message,
                type: 'warning',
                duration: 2000,
              })
          }
        })
        getSet()
      })
      .catch(() => {})
  }

  // 更新邀请码设置
  const handleUpdateInviteCodeSet = async () => {
    const res = await saveNetworkInviteCodeFn()
    ElMessage({
      type: res.code === 20000 ? 'success' : 'error',
      message: res.message,
    })
  }

  onMounted(() => {
    getSet()
    getworkTeamPageSelect('')
    if (inviteCodeSetFormRef.value) {
      inviteCodeSetFormRef.value.getNetworkInviteCodeSet()
    }
  })

  // 返回方法
  defineExpose({ getSet })
</script>

<template>
  <div class="set" v-loading="loading" element-loading-text="加载中...">
    <div class="set_form">
      <div class="bottom">
        <el-form ref="formRef" :model="form">
          <div class="form">
            <!-- 区域限制 -->
            <div>
              <el-form-item class="form_item">
                <template #label>
                  <div class="form_item_label">
                    <span class="name">区域限制</span>
                    <span class="tips">设定区域后，区域规则模式管理</span>
                  </div>
                </template>
                <div class="form_item_content">
                  <el-radio-group @change="saveSet" v-model="form.sectorise" class="el-group">
                    <el-radio :value="1">
                      <span class="bg_text">不限制</span>
                    </el-radio>
                    <el-radio :value="2">
                      <span class="bg_text">区域优先</span>
                    </el-radio>
                    <el-radio :value="3">
                      <span class="bg_text">限制区域</span>
                    </el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>
              <div class="bage"
                >选用区域优先或限制区域时，请保证所有服务商都设置了服务区域，否则设置不生效</div
              >
            </div>
          </div>
        </el-form>
      </div>
      <InviteCodeSetForm
        @update="handleUpdateInviteCodeSet"
        v-loading="saveNetworkInviteCodeLoading"
        ref="inviteCodeSetFormRef"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
